import defaultAvatar from '../images/01.jpg'
import { BASE_URL } from '@/api/baseurl.js'

/**
 * 获取用户头像URL
 * @param {string} fileName - 图片文件名
 * @returns {string} 头像URL
 */
export function getUserAvatarUrl(fileName) {
  if (!fileName) {
    return defaultAvatar
  }
  return `${BASE_URL}/api/Image/file/${fileName}`
}

/**
 * 全局带token的fetch，遇到401自动跳转登录
 * @param {string} url - 请求URL
 * @param {Object} options - 请求选项
 * @returns {Promise<Response>} 响应对象
 */
export async function fetchWithAuth(url, options = {}) {
  const token = localStorage.getItem('token')
  options.headers = options.headers || {}
  if (token) {
    options.headers['Authorization'] = 'Bearer ' + token
  }
  const response = await fetch(url, options)
  if (response.status === 401) {
    localStorage.removeItem('token')
    localStorage.removeItem('userId')
    localStorage.removeItem('username')
    alert('登录已过期，请重新登录')
    window.location.href = '/login'
    throw new Error('未授权')
  }
  return response
}

/**
 * 获取用户头像URL（先查数据库FileName）
 * @param {string} userId
 * @returns {Promise<string>} 头像URL
 */
export async function getUserAvatarByUserId(userId) {
  if (!userId) {
    console.log('用户ID为空，返回默认头像')
    return defaultAvatar
  }

  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${BASE_URL}/api/Image/avatar/${userId}`, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    if (response.status === 404) {
      // 没有头像，返回默认头像
      return defaultAvatar
    }
    if (!response.ok) {
      throw new Error(response.status)
    }
    const result = await response.json()
    if (
      result &&
      result.Data &&
      result.Data.fileName
    ) {
      // 返回头像图片URL
      return `${BASE_URL}/api/Image/file/${result.Data.fileName}?t=${Date.now()}`
    } else {
      return defaultAvatar
    }
  } catch (e) {
    console.error('获取用户头像失败:', e)
    return defaultAvatar
  }
}

/**
 * 根据用户ID获取头像文件名
 * @param {string} userId - 用户ID
 * @returns {Promise<string|null>} 头像文件名，如果没有头像则返回null
 */
export async function getUserAvatarFileName(userId) {
  if (!userId) {
    return null
  }

  try {
    const response = await fetchWithAuth(`${BASE_URL}/api/Image/avatar/${userId}`)
    if (response.ok) {
      const result = await response.json()
      if (result && result.Data && result.Data.hasAvatar && result.Data.fileName) {
        return result.Data.fileName
      } else {
        return null
      }
    } else {
      console.warn(`获取用户头像失败: ${response.status}`)
      return null
    }
  } catch (error) {
    console.error('获取用户头像失败:', error)
    return null
  }
}

/**
 * 获取用户头像，如果失败则返回默认头像
 * @param {string} fileName - 图片文件名
 * @returns {Promise<string>} 头像URL
 */
export async function getUserAvatar(fileName) {
  if (!fileName) {
    return defaultAvatar
  }

  try {
    const token = localStorage.getItem('token')
    const url = `${BASE_URL}/api/Image/file/${fileName}`
    const response = await fetch(url, { method: 'HEAD', headers: { Authorization: `Bearer ${token}` } })
    if (response.status === 404) {
      return defaultAvatar
    }
    if (response.ok) {
      return url
    } else {
      return defaultAvatar
    }
  } catch (error) {
    console.error('获取头像失败:', error)
    return defaultAvatar
  }
}

/**
 * 检查头像是否存在
 * @param {string} fileName - 图片文件名
 * @returns {Promise<boolean>} 是否存在
 */
export async function checkAvatarExists(fileName) {
  if (!fileName) {
    return false
  }

  try {
    const token = localStorage.getItem('token')
    const url = `${BASE_URL}/api/Image/file/${fileName}`
    const response = await fetch(url, { method: 'HEAD', headers: { Authorization: `Bearer ${token}` } })
    return response.ok
  } catch (error) {
    console.error('检查头像失败:', error)
    return false
  }
}

/**
 * 获取默认头像URL
 * @returns {string} 默认头像URL
 */
export function getDefaultAvatar() {
  return defaultAvatar
}

/**
 * 获取用户头像图片Blob并生成可用URL（带token认证）
 * @param {string} fileName - 图片文件名
 * @returns {Promise<string>} 可用的图片URL
 */
export async function getUserAvatarBlobUrl(fileName) {
  if (!fileName) {
    return defaultAvatar
  }
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${BASE_URL}/api/Image/file/${fileName}`, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    if (response.status === 404) {
      return defaultAvatar
    }
    if (!response.ok) {
      return defaultAvatar
    }
    const blob = await response.blob()
    return URL.createObjectURL(blob)
  } catch (e) {
    console.error('获取头像Blob失败:', e)
    return defaultAvatar
  }
} 